package tq.com.tqteacher.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.scroll.CropScrollHandle;

import java.io.File;
import java.util.ArrayList;

import tq.com.download.IDownloadListener;
import tq.com.download.TQDownloadManager;
import tq.com.tqcom.base.BaseActivity;
import tq.com.tqcom.util.ImgUtils;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqcom.view.TQProcessBar;
import tq.com.tqteacher.R;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.net.TQNetInterface;
import tq.com.tqteacher.view.TQHeader3ViewHold;

public class TQPdfReaderActivity extends BaseActivity {
    private PDFView mPDFView;
    private TQHeader5View mHeader5View;
    private TextView commit;
    private TQProcessBar mProcessBar;

    final static public int ACTIVITY_TYPE_READ = 0x00;
    final static public int ACTIVITY_TYPE_CROP = 0x01;
    final static public int ACTIVITY_TYPE_SELECT = 0x02;
    final static public String OPEN_TYPE_KEY = "OPEN_TYPE_KEY";
    final static public String OPEN_PATH_KEY = "OPEN_PATH_KEY";
    final static public String MAX_CROP_KEY = "MAX_CROP_KEY";

    final static public int REQUEST_CROP_CODE = 0x11;
    final static public String RESULT_KEY = "CROP_RESULT";

    private int openType = ACTIVITY_TYPE_READ;
    private ArrayList<String>cropsets = new ArrayList<>();
    private int maxCrop = 0;
    private TQDownloadManager.Build mBuild;

    private String url;
    static public void showRead(Activity pActivity, String url){
        Intent intent = new Intent(pActivity, TQPdfReaderActivity.class);
        intent.putExtra(OPEN_TYPE_KEY, ACTIVITY_TYPE_READ);
        intent.putExtra(OPEN_PATH_KEY, url);
        pActivity.startActivity(intent);
    }

    static public void showCrop(Activity pActivity, String url, int requestCode){
        Intent intent = new Intent(pActivity, TQPdfReaderActivity.class);
        intent.putExtra(OPEN_TYPE_KEY, ACTIVITY_TYPE_CROP);
        intent.putExtra(OPEN_PATH_KEY, url);
        pActivity.startActivityForResult(intent, requestCode);
    }

    static public void showCrop(Activity pActivity, String url, int requestCode, int max){
        Intent intent = new Intent(pActivity, TQPdfReaderActivity.class);
        intent.putExtra(OPEN_TYPE_KEY, ACTIVITY_TYPE_CROP);
        intent.putExtra(OPEN_PATH_KEY, url);
        intent.putExtra(MAX_CROP_KEY, max);
        pActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStatusBar();

        setContentView(R.layout.activity_pdf_reader_layout);

        mHeader5View = findViewById(R.id.title);
        mPDFView = findViewById(R.id.pdfView);
        commit = findViewById(R.id.commit);
        mProcessBar = findViewById(R.id.process_bar);
        mProcessBar.updateProcess(0);

        openType = getIntent().getIntExtra(OPEN_TYPE_KEY, ACTIVITY_TYPE_READ);
        maxCrop = getIntent().getIntExtra(MAX_CROP_KEY, 0);
        url = getIntent().getStringExtra(OPEN_PATH_KEY);

        if(openType == ACTIVITY_TYPE_CROP){
            mHeader5View.getTitleView().setText("截取");
//            mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    TQPublishType.setCropPic(cropsets, TQPdfReaderActivity.this);
//                }
//            });
            mHeader5View.getRightView().setText("完成截取(0)");
        }else if(openType == ACTIVITY_TYPE_SELECT){
            mHeader5View.getTitleView().setText("选择");
            commit.setVisibility(View.VISIBLE);
        }else{
            mHeader5View.getTitleView().setText("阅读");
        }


        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(openType == ACTIVITY_TYPE_SELECT){
                    selectResult();
                }

            }
        });
        
        mHeader5View.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");
                if(openType == ACTIVITY_TYPE_CROP){
                    cropResult();
                }
            }
        });

        mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if(maxCrop == 1){
            mHeader5View.getRightView().setVisibility(View.INVISIBLE);
        }

        if(TQDownloadManager.checkCahce(url, ".pdf")){
            String local = TQDownloadManager.cachePath(url, ".pdf");
            openPdf(local);
            mProcessBar.setVisibility(View.GONE);
        }else{
            TQDownloadManager.Build lBuild = new TQDownloadManager.Build()
                    .setFileId(url)
                    .setFileType(".pdf")
                    .setListener(mDownloadListener);

            lBuild.start();
            mBuild = lBuild;
            mProcessBar.setVisibility(View.VISIBLE);
        }

    }

    private OnLoadCompleteListener mOnLoadCompleteListener = new OnLoadCompleteListener() {
        @Override
        public void loadComplete(int nbPages) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(mBuild != null){
            mBuild.cancel();
        }
    }

    private void selectResult(){
        Intent intent = new Intent();
        intent.putExtra(RESULT_KEY, url);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void cropResult(){
        Intent intent = new Intent();
        intent.putExtra(RESULT_KEY, cropsets);
        setResult(RESULT_OK, intent);
        finish();
    }

    private CropScrollHandle.CaptureBitmap mCaptureBitmap = new CropScrollHandle.CaptureBitmap() {
        @Override
        public void doCapture(Bitmap pBitmap) {
            String result = ImgUtils.saveImageToGallery(TQPdfReaderActivity.this, pBitmap);
            cropsets.add(result);

            if(cropsets.size() == maxCrop && maxCrop == 1){
                cropResult();
            }

            mHeader5View.getRightView().setText(String.format("完成截取(%d)", cropsets.size()));
//            Intent intent = new Intent();
//            intent.putExtra(RESULT_KEY, result);
//
//            TQPdfReaderActivity.this.setResult(RESULT_OK, intent);
//            TQPdfReaderActivity.this.finish();
        }
    };

    private void openPdf(String local){
        PDFView.Configurator lConfigurator = mPDFView.fromFile(new File(local));//mPDFView.fromAsset("effective-go-zh-en-gitbook.pdf");

        lConfigurator
                .spacing(5)
                .enableAntialiasing(true)
                .enableAnnotationRendering(true)
                .onLoad(mOnLoadCompleteListener)
                .swipeHorizontal(false)
                .enableDoubletap(false)
                .enableScale(false);

        if(openType == ACTIVITY_TYPE_CROP) {
            lConfigurator.scrollHandle(new CropScrollHandle(this, mCaptureBitmap));
        }

        lConfigurator.load();
    }

    private IDownloadListener mDownloadListener = new IDownloadListener() {
        @Override
        public void process(long current, long total) {
            Log.d(TAG, String.format("current== %d, total === %d", current, total));
            int t = (int) ((current / (total * 1.0f)) * 100);
            mProcessBar.updateProcess(t);
        }

        @Override
        public void fail(String msg) {
            Log.d(TAG, "fail: ");
            mProcessBar.setText("下载文件失败，请稍后重试");
            mBuild = null;
        }

        @Override
        public void success(String local) {
            Log.d(TAG, "success: ");
            mProcessBar.setVisibility(View.GONE);

            openPdf(local);
            mBuild = null;
        }
    };
}
